/*
* 新人专区添加编辑商品
* @Author: Li Yujie
* @Date: 2020-11-23
*/
<template>
    <div class="wrapper">
        <div class="content-wrapper">
            <!-- header -->
            <div class="header">
                <div class="header-title">
                    {{ type === 'add' ? '添加新人专区商品' : '编辑新人专区商品' }}
                </div>
            </div>
            <!-- /header -->

            <!--表单-->
            <el-form
                :model="ruleForm"
                :rules="rules"
                label-position="right"
                ref="ruleForm"
                label-width="160px"
                class="form-wrap"
            >
                <el-form-item
                    label="选择自营商品"
                    prop="goods_no"
                    v-if="type === 'add'"
                >
                    <el-button
                        size="medium"
                        type="primary"
                        @click="$refs.goodsSelect.show(1, requestUrl)"
                    >
                        选择商品
                    </el-button>
                </el-form-item>
                <el-form-item
                    label="商品缩略图"
                    v-if="ruleForm.goods_cover"
                >
                    <img
                        :src="ruleForm.goods_cover"
                        alt="加载失败"
                        style="width:80px;height:80px"
                        @click="fnShowPreview(ruleForm.goods_cover)"
                    >
                </el-form-item>
                <el-form-item
                    label="商品原标题"
                    v-if="ruleForm.goods_title"
                >
                    {{ ruleForm.goods_title }}
                </el-form-item>
                <el-form-item
                    label="商品编号"
                >
                    {{ ruleForm.goods_no }}
                </el-form-item>
                <el-form-item
                    label="商品标题"
                    prop="welfare_title"
                >
                    <el-input
                        v-model="ruleForm.welfare_title"
                        size="medium"
                        clearable
                        style="width: 380px"
                    />
                    <span class="tips">新人专区活动页显示的商品标题</span>
                </el-form-item>
                <el-form-item label="新人价和活动库存设置">
                    <el-table
                        :data="ruleForm.price_list"
                        style="width: 100%;border: 1px solid #eee"
                        class="data-table product"
                        @selection-change="handleSelectAll($event)"
                    >
                        <el-table-column
                            type="selection"
                            align="center"
                            width="48"
                        >
                            <template slot-scope="scope">
                                <el-form-item style="margin-bottom: 20px">
                                    <el-checkbox
                                        v-model="scope.row.check_status"
                                        :true-label="1"
                                        :false-label="0"
                                    />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="商品规格"
                            show-overflow-tooltip
                            :formatter="emptyFormatter"
                            width="200"
                        >
                            <template slot-scope="scope">
                                <el-form-item style="margin-bottom: 20px">
                                    {{ scope.row.spec_list | filterSpec }}
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="product_price"
                            label="原售价"
                            show-overflow-tooltip
                            align="center"
                            :formatter="emptyFormatter"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    style="margin-bottom: 20px"
                                >
                                    {{ scope.row.product_price }}
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="新人价（元）"
                            align="center"
                            width="120"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    :prop="`price_list[${scope.$index}]`"
                                    :rules="rules.welfare_price"
                                    style="margin-bottom: 20px"
                                >
                                    <el-input
                                        v-model="scope.row.welfare_price"
                                        style="width: 98px"
                                        size="medium"
                                        :disabled="scope.row.check_status === 0"
                                        @click.native="clickDisableInput(scope.row)"
                                        @blur="calcPlatformMoney(scope.row)"
                                    />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="活动库存"
                            width="240"
                        >
                            <template slot-scope="scope">
                                <div
                                    class="input-wrapper"
                                    style="display: flex; align-items: center;margin-bottom: 20px"
                                >
                                    <el-select
                                        v-model="scope.row.stock_type"
                                        :style="{width: scope.row.stock_type === 1 ? '138px' : '108px'}"
                                        size="medium"
                                        :disabled="scope.row.check_status === 0"
                                        @change="handleStockTypeChange($event, scope.$index)"
                                        @click.native="clickDisableInput(scope.row)"
                                    >
                                        <el-option
                                            label="同步商家库存"
                                            :value="1"
                                        />
                                        <el-option
                                            label="自定义"
                                            :value="2"
                                        />
                                    </el-select>
                                    <el-form-item
                                        v-if="scope.row.stock_type === 2"
                                        :prop="`price_list[${scope.$index}]`"
                                        :rules="rules.welfare_stock"
                                    >
                                        <el-input
                                            v-model="scope.row.welfare_stock"
                                            style="width: 88px;margin-left: 10px"
                                            size="medium"
                                            :disabled="scope.row.check_status === 0"
                                            @click.native="clickDisableInput(scope.row)"
                                        />
                                    </el-form-item>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="product_stock"
                            label="商家库存"
                            show-overflow-tooltip
                            align="center"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    style="margin-bottom: 20px"
                                >
                                    {{ scope.row.product_stock }}
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="是否平台补贴"
                            align="center"
                            width="200px"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    style="margin-bottom: 20px"
                                >
                                    <el-select
                                        v-model="scope.row.shop_subsidy_enable"
                                        size="medium"
                                        style="width: 140px"
                                        :disabled="scope.row.check_status === 0"
                                        @click.native="clickDisableInput(scope.row)"
                                        @change="calcPlatformMoney(scope.row, 'clear')"
                                    >
                                        <el-option
                                            label="平台补贴"
                                            :value="1"
                                        />
                                        <el-option
                                            label="商家全部补贴"
                                            :value="0"
                                        />
                                        <el-option
                                            label="商家部分补贴"
                                            :value="2"
                                        />
                                    </el-select>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="商家补贴金额（元）"
                            width="200px"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    :prop="`price_list[${scope.$index}]`"
                                    :rules="rules.shop_subsidy_money_by_shop"
                                    style="margin-bottom: 20px"
                                >
                                    <el-input
                                        v-model="scope.row.shop_subsidy_money_by_shop"
                                        placeholder="商家补贴金额"
                                        size="medium"
                                        clearable
                                        style="width: 120px"
                                        :disabled="scope.row.shop_subsidy_enable !== 2 || scope.row.check_status === 0"
                                        @blur="calcPlatformMoney(scope.row)"
                                        @click.native="clickDisableInput(scope.row)"
                                    />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="平台补贴金额（元）"
                            align="center"
                            width="200px"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    style="margin-bottom: 20px"
                                >
                                    {{ scope.row.shop_subsidy_money_by_platform }}
                                </el-form-item>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item
                    label="佣金比例"
                    prop="commission_rate"
                >
                    <el-input
                        v-model="ruleForm.commission_rate"
                        size="medium"
                        clearable
                        style="width: 380px"
                    >
                        <span
                            slot="suffix"
                            style="margin-right: 5px"
                        >%</span>
                    </el-input>
                </el-form-item>
                <el-form-item
                    label="排序号"
                    prop="welfare_sort"
                >
                    <el-input
                        v-model="ruleForm.welfare_sort"
                        size="medium"
                        clearable
                        style="width: 380px"
                    />
                </el-form-item>
                <el-form-item
                    label="活动状态设置"
                >
                    <el-switch
                        v-model="ruleForm.welfare_status"
                        active-text="上架"
                        inactive-text="下架"
                        :active-value="1"
                        :inactive-value="0"
                    />
                </el-form-item>
            </el-form>
            <!--/表单-->

            <div class="btn-group">
                <el-button
                    size="medium"
                    style="width: 120px"
                    @click="handleCancel()"
                >
                    取消
                </el-button>
                <el-button
                    size="medium"
                    type="primary"
                    style="width: 120px"
                    @click="handleSubmit()"
                >
                    完成
                </el-button>
            </div>
        </div>

        <!--商品选择弹窗-->
        <goods-select
            ref="goodsSelect"
            @change="handleSelectGoods"
        />
        <!-- 图片预览 -->
        <img-preview ref="preview"/>

        <!-- 预算提示弹窗 -->
        <show-dialog
            ref="showDialog"
            :dialog="showDialog"
            :width="360"
            :cancel-text="'取消'"
            :confirm-text="'确定'"
            :title="'温馨提示'"
            :content="`当前新人专区的平台补贴支出在计划时间${ '2021/5/24-2021/6/24' }已无预算，暂无法添加新人专区商品`"
            @close="showDialog = false"
            @emit="emitFun"
        />
    </div>
</template>

<script>
import showDialog from '@/components/common/dialog.vue';
import {back} from '@/mixin/back';
import GoodsSelect from '@/components/goods/goods-select';
import imgPreview from '@/components/common/img-preview';
const numberReg = /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0)$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/;

export default {
    name: "NewPeopleEdit",
    data() {
        const validatePrice = (rule, value, callback) => {
            if (value.check_status && value.welfare_price === '') {
                callback(new Error('请填写新人价'));
            } else if (value.welfare_price && !numberReg.test(value.welfare_price)) {
                callback(new Error('新人价必须未数字'));
            } else if (value.welfare_price && Number(value.welfare_price) > value.product_price) {
                callback(new Error('价格应小于原售价'));
            } else {
                callback();
            }
        };
        const validateStock = (rule, value, callback) => {
            if (value.check_status && value.welfare_stock === '') {
                callback(new Error('请填写活动库存'));
            } else if (value.welfare_stock && !/^\d{1,}$/.test(value.welfare_stock)) {
                callback(new Error('库存必须未数字'));
            } else if (value.welfare_stock && Number(value.welfare_stock) > value.product_stock) {
                callback(new Error('库存应小于总库存'));
            } else {
                callback();
            }
        };
        const validateSubsidy = (rule, value, callback) => {
            if (value.check_status && value.shop_subsidy_money_by_shop === '') {
                callback(new Error('请填写补贴金额'));
            } else if (value.shop_subsidy_money_by_shop && !numberReg.test(value.shop_subsidy_money_by_shop)) {
                callback(new Error('金额必须未数字'));
            } else {
                callback();
            }
        };

        return {
            type: 'add',
            ruleForm: {
                welfare_no: '',
                // 商品编号
                goods_no: '',
                // 原商品标题
                goods_title: '',
                welfare_title: '',
                // 封面图
                goods_cover: '',
                // 排序号
                welfare_sort: 99,
                commission_rate: '',
                // 上架状态
                welfare_status: 0,
                // 规格价格列表
                price_list: [],
            },
            // 校验规则
            rules: {
                goods_no: [
                    { required: true, message: '请选择商品', trigger: 'blur' }
                ],
                welfare_title: [
                    { required: true, message: '商品标题不能为空', trigger: 'blur' }
                ],
                welfare_price: [
                    { validator: validatePrice, trigger: 'blur' },
                ],
                welfare_stock: [
                    { validator: validateStock, trigger: 'blur' },
                ],
                shop_subsidy_money_by_shop: [
                    {validator: validateSubsidy, trigger: 'blur'}
                ],
                welfare_sort: [
                    { required: true, message: '排序号不能为空', trigger: 'blur' },
                    { pattern: /^\d{1,}$/, message: '排序号必须为数字', trigger: 'blur' }
                ],
                commission_rate: [
                    { required: true, message: '佣金比例不能为空', trigger: 'blur' },
                    { pattern: numberReg, message: '佣金比例必须为数字', trigger: 'blur' }
                ]
            },
            showDialog: false,
            requestUrl: '/student/shop_welfare%5Cget_goods_list'
        };
    },
    mixins: [back],
    filters: {
        filterSpec (val) {
            if(!val) return '';
            let str = '';

            val.forEach(el => {
                str += el.spec_name + ':' + el.spec_value + '；';
            });
            return str;
        }
    },
    components: {
        GoodsSelect,
        imgPreview,
        showDialog
    },
    mounted() {
        let query = this.$route.query;

        this.$store.commit('SET_HEADER', [{title: "APP后台"}, {title: '商城'}, {title: '新人专区', path: '/student/new-people-list'}, {title: '添加新人专区商品'}]);
        if(query.no) {
            this.type = 'edit';
            this.ruleForm.welfare_no = query.no;
            this.getDetail();
        } else {
            this.type = 'add';
        }
    },
    methods: {
        /**
         * 获取选择的商品
         * @param val
         */
        handleSelectGoods(val) {
            this.ruleForm.goods_title = val.goods_title;
            this.ruleForm.welfare_title = val.goods_title;
            this.ruleForm.goods_no = val.goods_no;
            this.ruleForm.goods_price = val.goods_price;
            this.ruleForm.goods_cover = val.goods_cover;
            this.ruleForm.commission_rate = val.goods_commission_rate;

            // 请求产品规格列表
            this.$post('/student/shop_welfare%5Cget_product_list', {
                goods_no: this.ruleForm.goods_no
            }, resp => {
                if (resp.code === 1) {
                    let price_list = [...resp.data.product_list];

                    price_list.map(item => {
                        item.welfare_price = '';
                        item.welfare_stock = 0;
                        this.$set(item, 'stock_type', 1);
                        this.$set(item, 'shop_subsidy_enable', 1);
                        this.$set(item, 'shop_subsidy_money_by_shop', 0);
                        this.$set(item, 'shop_subsidy_money_by_platform', (Number(item.product_price) - Number(item.welfare_price)).toFixed(2));
                    });

                    this.ruleForm.price_list = price_list;
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        duration: 2000,
                        type: 'warning'
                    });
                }
            });
        },
        /**
         * 查看图片
         * @param   {String}    images      //单图预览
         * @param   {Array}     images      //多图预览
         */
        fnShowPreview(images) {
            if (images && Object.prototype.toString.call(images) == '[object String]') {
                this.$refs.preview.show([
                    images
                ]);
            } else if (images && Object.prototype.toString.call(images) == '[object Array]') {
                this.$refs.preview.show(images);
            } else {
                this.$message({
                    type: 'warning',
                    message: '图片类型错误'
                });
            }
        },

        /**
         * 提交
         */
        handleSubmit() {
            this.$refs.ruleForm.validate((valid) => {
                if(valid) {
                    let params = {...this.ruleForm};

                    params.product_json = JSON.stringify(params.price_list);
                    delete params.price_list;
                    this.$post('/student/shop_welfare%5Csave', params, resp => {
                        if (resp.code === 1) {
                            const next = () => {
                                this.$notify({
                                    title: '提示',
                                    message: '保存成功',
                                    type: 'success',
                                    duration: 2000
                                });
                                setTimeout(() => {
                                    this.$router.push({
                                        path: '/student/new-people-list'
                                    });
                                }, 500);
                            };

                            if(resp.data.result === 1) {
                                next();
                            } else {
                                this.$zdConfirm(`当前新人专区的平台补贴支出${resp.data.result === -1 ? '不在财控计划时间内' : '在计划时间已无预算'} ，暂无法添加新人专区商品，如需要增加预算，请联系平台财务人员。`, '温馨提示', {
                                    confirmButtonText: '知道了',
                                    hasCancelButton: false,
                                    type: 'warning'
                                }).then(() => {});
                            }
                        } else {
                            this.$notify({
                                title: '提示',
                                message: resp.msg,
                                duration: 2000,
                                type: 'warning'
                            });
                        }
                    });

                }
            });
        },

        emitFun () {
            setTimeout(() => {
                this.$router.push({
                    path: '/student/new-people-list'
                });
            }, 500);
        },

        /**
         * 返回列表
         */
        handleCancel() {
            this.$confirm('返回后将不会保存您所修改的内容,是否返回?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$router.push({
                    path: '/student/new-people-list'
                });
            });
        },

        /**
         * 编辑时获取详情
         */
        getDetail() {
            let params = {
                welfare_no: this.ruleForm.welfare_no
            };

            this.$post('/student/shop_welfare%5Cget', params, resp => {
                if (resp.code === 1) {
                    this.ruleForm.goods_no = resp.data.goods_no;
                    this.ruleForm.goods_price = resp.data.goods_price;
                    this.ruleForm.goods_title = resp.data.goods_title;
                    this.ruleForm.welfare_no = resp.data.welfare_no;
                    this.ruleForm.welfare_price =resp.data.welfare_price;
                    this.ruleForm.welfare_sort = resp.data.welfare_sort;
                    this.ruleForm.welfare_status = resp.data.welfare_status;
                    this.ruleForm.welfare_title = resp.data.welfare_title;
                    this.ruleForm.commission_rate = resp.data.commission_rate;

                    this.getProductList();
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        duration: 2000,
                        type: 'warning'
                    });
                }
            });
        },

        /**
         * 详情时获取产品规格信息
         */
        getProductList() {
            let params = {
                goods_no: this.ruleForm.goods_no,
                welfare_no: this.ruleForm.welfare_no
            };

            this.$post('/student/shop_welfare%5Cget_product_list', params, resp => {
                if (resp.code === 1) {
                    resp.data.product_list.forEach(item => {
                        this.$set(item, 'stock_type', item.welfare_stock === -1 ? 1 : 2);
                        this.calcPlatformMoney(item);
                    });
                    this.ruleForm.price_list = resp.data.product_list;
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        duration: 2000,
                        type: 'warning'
                    });
                }
            });
        },

        /**
         * 全选
         * @param selection
         */
        handleSelectAll(selection) {
            this.ruleForm.price_list.forEach(item => {
                this.$set(item, 'check_status', selection.length ? 1 : 0);
            });
        },

        /**
         * @description 过滤函数
         */
        emptyFormatter(row, column, val) {
            if (!val) return '--';
            return val;
        },

        /**
         * 选择库存类型
         * @param val
         * @param index
         */
        handleStockTypeChange(val, index) {
            if(val === 1) {
                this.ruleForm.price_list[index].welfare_stock = -1;
            } else {
                this.ruleForm.price_list[index].welfare_stock = 0;
            }
        },

        /**
         * 点击禁用的input
         * @param row
         */
        clickDisableInput(row) {
            if(!row.check_status) {
                this.$message.warning('请勾选该规格');
            }
        },

        /**
         * 计算平台与商家补贴金额
         * @param row
         * @param type
         */
        calcPlatformMoney(row, type) {
            let product_price = Number(row.product_price);
            let welfare_price = Number(row.welfare_price);
            let subsidy_money_all = (product_price - welfare_price).toFixed(2);

            // 平台全部补贴
            if(row.shop_subsidy_enable === 1) {
                this.$set(row, 'shop_subsidy_money_by_shop', 0);
                this.$set(row, 'shop_subsidy_money_by_platform', subsidy_money_all);
            }
            // 商家全部补贴
            if(row.shop_subsidy_enable === 0) {
                this.$set(row, 'shop_subsidy_money_by_shop', subsidy_money_all);
                this.$set(row, 'shop_subsidy_money_by_platform', 0);
            }
            // 商家部分补贴
            if(row.shop_subsidy_enable === 2) {
                if(type) {
                    this.$set(row, 'shop_subsidy_money_by_shop', '');
                }
                let shop_subsidy_money_by_platform = subsidy_money_all - Number(row.shop_subsidy_money_by_shop);

                this.$set(row, 'shop_subsidy_money_by_platform', shop_subsidy_money_by_platform < 0 ? '0.00' : shop_subsidy_money_by_platform.toFixed(2));
            }
        }
    }
};
</script>

<style scoped lang="less">
.wrapper {
    width: 100%;
    position: relative;
    box-sizing: border-box;

    .content-wrapper {
        display: flex;
        height: calc(100% - 24px);
        flex-direction: column;
        position: relative;
        margin: 12px;
        background: #fff;
        box-sizing: border-box;
        overflow-y: auto;
        &::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
        /*header*/

        .header {
            height: 68px;
            padding: 24px;
            box-sizing: border-box;
            box-shadow: 0px -1px 0px 0px #F0F2F5;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #F0F2F5;

            .header-title {
                color: #333333;
                font-size: 20px;
                height: 20px;
                font-weight: 500;
                position: relative;
                margin: 24px 0 24px 12px;

                &::before {
                    content: '';
                    position: absolute;
                    left: -8px;
                    top: -1px;
                    width: 3px;
                    height: 20px;
                    background: #1890FF;
                }
            }
        }

        /*表单*/

        .form-wrap {
            padding: 30px;

            .zd-spec {
                display: flex;
                font-size: 14px;
                padding-right: 12px;
                .zd-spec-luck-text {
                    margin-right: 10px;
                }
            }

            /deep/ .el-checkbox-group {
                display: flex;
                flex-direction: column;

                .zd-spec {
                    display: flex;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;

                    .zd-spec-text {
                        font-size: 14px;
                        margin-right: 10px;
                    }
                }
                .el-checkbox {
                    width: min-content;
                }
            }

            .tips {
                margin-left: 24px;
                font-size: 14px;
                color: #999;
            }
        }
        .btn-group {
            margin-left: 120px;
            padding-bottom: 36px;
            .el-button {
                margin: 0 24px;
            }
        }
        /deep/ .el-table {
            th {
                background: #f2f2f2!important;
            }
            td {
                border-bottom: 0!important;
                background: #FBFBFB!important;
            }
        }
        /deep/ .el-table.product {
            background: #FBFBFB!important;
            .el-table__body-wrapper {
                padding-top: 12px;
            }
        }
    }
    // 表格
    .data-table {
        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
    }
}
</style>
